<template>
  <!-- <div class="user">
    <div class="user-head">
      <div class="user-head_left">
        <user-outlined />
        <span style="margin-left: 10px;">平台用户</span>
      </div>
      <div class="user-head_right">
        <a-space>
          <a-button type="primary" style="border-radius: unset;" @click="showAddModal">
            <template #icon><plus-outlined /></template>
            新增
          </a-button>
          <a-button style="border-radius: unset;" @click="exportData" :loading="exportLoading">
            <template #icon><cloud-download-outlined /></template>
            导出
          </a-button>          
        </a-space>
      </div>
    </div>
    <div class="user-container">
        <div class="user-container_left">
            <SearchTree :tree-data="treeData" @selected="handleSelected"></SearchTree>
        </div>
        <div class="user-container_right">
          <div class="user-options">
            <OptionView
              @search="handleSearch"
              @reset="fetchUserList"
              @selected="handleStatus"
            ></OptionView>
          </div>
          <div class="user-table">
            <TableView
              :jsonData="jsonData"
              @status="changeStatus"
              @change="handleTableChange"
              @edit="showEditModal"
              @delete="handleDelete"
            ></TableView>
            
             
          </div>
        </div>        
    </div>
  </div> -->
  <!-- <EditModal
    :title="modalTitle"
    :inital-values="formState"
    :open="isOpenModal" 
    @cancel="closeModal"
    @submit="handleSubmit"
  >
  </EditModal> -->
  <div></div>
</template>

<script lang="ts" setup>
import { addUser, deleteUser, getAllUserList, getUserList, searchUser, selectedOrganization, selectedStatus, switchStatus, updateUser } from '@/api/user/user';
import EditModal from '@/components/modal/EditModal.vue';
import OptionView from '@/components/OptionView.vue';
import SearchTree from '@/components/SearchTree.vue';
import { exportAllToExcel } from '@/utils/exportExcel';
import { 
  UserOutlined,
  PlusOutlined,
  CloudDownloadOutlined
} from '@ant-design/icons-vue';
import { message, Modal, TableColumnsType } from 'ant-design-vue';
import { onMounted, reactive, ref } from 'vue';

interface TreeNode {
    key: string
    title: string
    children?: TreeNode[]
}
interface DataItem {
  id: number;
  account: string;
  name: string;
  role: string;
  phone: string;
  organization: string;
  status: boolean;
}
interface KeyType{
    account:string, 
    name: string, 
    phone: string
}

const treeData: TreeNode[] = [
  {
    title: 'HY环境科技',
    key: '1',
    children: [
      { 
        title: '运营部', 
        key: '1-1',
        children: [
          { title: '人事部', key: '1-1-1' }
        ] 
      },
      { title: '研发部', key: '1-2' },
    ],
  },
];
const tableData = reactive({
    data: [{}] as DataItem[],
    total: 0
})
const loading = ref<boolean>(false)
const pagination = reactive({
    current: 1,
    pageSize: 10,
    total: 0,
    showSizeChanger: true,
    showTotal: (total: number) => `共${total}条`
})

const fetchUserList = async () => {
    loading.value = true
    try{
        const res = await getUserList({
          current: pagination.current,
          pageSize: pagination.pageSize
        })
        tableData.data = res.data.list;
        pagination.total = res.data.total
    }finally{
        loading.value = false
    }
}

const searchUserList = async (values: KeyType) => {
  loading.value = true
  try{
    const res = await searchUser({
      keywords: values,
      current: pagination.current,
      pageSize: pagination.pageSize
    })
    tableData.data = res.data.list
    tableData.total = res.data.total
  }finally{
    loading.value = false
  }
}

const selectedOrg = async (values: string) => {
  loading.value = true
  try{
    const res = await selectedOrganization({
      keywords: values,
      current: pagination.current,
      pageSize: pagination.pageSize
    })
    tableData.data = res.data.list
    tableData.total = res.data.total
  }finally{
    loading.value = false
  }
}

const selectedSta = async (values: boolean) => {
  loading.value = true
  try{
    const res = await selectedStatus({
      keywords: values,
      current: pagination.current,
      pageSize: pagination.pageSize
    })
    tableData.data = res.data.list
    tableData.total = res.data.total
  }finally{
    loading.value = false
  }
}

const switchS = async (values: boolean) => {
  try {
    await switchStatus(values)
    message.success('切换成功')
  } catch (error) {
    message.error('切换失败')
  }
}

//处理选择账号状态
const status = ref<boolean>()
const handleStatus = (values: string) => {
  pagination.current = 1
  if(values === '全部'){
    fetchUserList()
  }else{
    if(values === '开启'){
      status.value = true
      selectedSta(status.value)
    }else{
      status.value = false
      selectedSta(status.value)
    }
  }
}

//处理开关状态
const changeStatus = (status: boolean) => {
  switchS(status)
}

//处理选择组织
const handleSelected = (values: string) =>{
  pagination.current = 1
  selectedOrg(values)
}

//处理搜索
const handleSearch = (values: KeyType) => {
  pagination.current = 1
  searchUserList(values)
}

//处理表格分页
const handleTableChange  = ({ current, pageSize }: { current: number, pageSize: number }) => {
  pagination.current = current
  pagination.pageSize = pageSize
  fetchUserList()
}

//对话框
const isOpenModal = ref<boolean>(false)
const modalTitle = ref('新增用户')
const formState = ref<DataItem>({
  id: 0,
  account: '',
  name: '',
  role: '',
  phone: '',
  organization: '',
  status: false
})

const showAddModal = () => {
  modalTitle.value = '新增用户'
  formState.value = { 
    id: 0,
    account: '',
    name: '',
    role: '',
    phone: '',
    organization: '',
    status: false
   }
  isOpenModal.value = true
}

const showEditModal = ( record: DataItem ) => {
  modalTitle.value = '编辑用户'
  formState.value = { ...record }
  isOpenModal.value = true
}

const handleSubmit = async (values: any) => {
  try {
    if(values.id === 0){
      const { id, ...data } = values
      await addUser(data)
      message.success('新增成功')
    }else{
      await updateUser(values)
      message.success('更新成功')
    }
    closeModal()
    fetchUserList()
  }catch(error){
    message.error('操作失败')
  }
}

const handleDelete = (record: DataItem) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定删除用户${record.name}吗？`,
    onOk: async () => {
      await deleteUser(record.id).then((res: any) => {
        if(res.code === 200){
          message.success('删除成功')
          fetchUserList()
        }else{
          message.error('删除失败')
        }
      })
      
    }
  })
}

const closeModal = () => {
  isOpenModal.value = false
}

//导出数据
const exportLoading = ref(false)
const exportData = async () => {
  exportLoading.value = true
  try {
    await exportAllToExcel(async () => {
      const res = await getAllUserList()
      return res.data.list
    },'用户数据',[
      {
        key: 'id', title: 'ID'
      },
      {
        key: 'account', title: '用户账号'
      },
      {
        key: 'name', title: '用户姓名'
      },
      {
        key: 'role', title: '角色名称'
      },
      {
        key: 'phone', title: '手机号码'
      },
      {
        key: 'organization', title: '组织名称'
      },
    ])
  } catch (error) {
    console.log(error);
  }finally{
    exportLoading.value = false
  }
}

const columns = ref<TableColumnsType>([
  { title: '用户账号', dataIndex: 'account',resizable: true, key: 'account', minWidth:100,width:100},
  { title: '用户姓名', dataIndex: 'name',resizable: true, key: 'name', minWidth:100,width:100},
  { title: '角色名称', dataIndex: 'role', key: 'role',resizable: true, minWidth:100,width:100 },
  { title: '手机号码', dataIndex: 'phone', key: 'phone',resizable: true, minWidth:100,width:100 },
  { title: '组织架构', dataIndex: 'organization', key: 'organization',resizable: true, minWidth:100,width:100 },
  { title: '账号状态', dataIndex: 'status', key: 'status', },
  { title: '操作', key: 'operation', fixed: 'right', width:200},
])

//
const tableView = {
  columns: columns.value, //表格列表头
  tableData: tableData.data, //表格数据
  pagination: pagination, //分页信息
  loading: loading.value, //加载状态
  
}

const jsonData = reactive([
  {
    content: tableView,
    parentCode: "001",
    index: "TableView",
  }
])

onMounted(() => {
  fetchUserList()
})

</script>
 
<style scoped>
.user-head{
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 45px;
  border-bottom: 1px solid #f0f0f0;
}
.user-head_left{
  margin: 10px;
  font-size: 18px;
}
.user-head_left:hover{
  color: #29a2ff;
}
.user-head_right{
  margin: 10px;
  font-size: 14px;
}

.user-container{
  display: flex;
  margin: 10px;
  min-height: 360px;
}
.user-container_left{
  width: 180px; 
}
.user-container_right{
  max-width: 100%;
  width: 0;
  flex: 1;
}
.user-options{
  margin-left: 25px;
  margin-top: 10px;
  max-width: 100%;
}

.user-table{
  margin: 10px;
}


</style>